import { createStore } from 'vuex'

export default createStore({
  state: {
    // 用户相关
    userRole: localStorage.getItem('userRole') || '',
    token: localStorage.getItem('token') || '',
    
    // 页面状态
    loadingStatus: false,
    systemError: null,
    
    // 患者相关
    currentPatient: JSON.parse(localStorage.getItem('currentPatient')) || {}
  },
  getters: {
    isAuthenticated(state) {
      return !!state.token
    },
    userRole(state) {
      return state.userRole
    },
    isLoading(state) {
      return state.loadingStatus
    },
    currentPatient(state) {
      return state.currentPatient
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    setUserRole(state, role) {
      state.userRole = role
      localStorage.setItem('userRole', role)
    },
    clearAuth(state) {
      state.token = ''
      state.userRole = ''
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
    },
    setLoading(state, status) {
      state.loadingStatus = status
    },
    setError(state, error) {
      state.systemError = error
    },
    clearError(state) {
      state.systemError = null
    },
    setCurrentPatient(state, patient) {
      state.currentPatient = patient
      localStorage.setItem('currentPatient', JSON.stringify(patient))
    },
    clearCurrentPatient(state) {
      state.currentPatient = {}
      localStorage.removeItem('currentPatient')
    }
  },
  actions: {
    login({ commit }, { token, role }) {
      commit('setToken', token)
      commit('setUserRole', role)
    },
    logout({ commit }) {
      commit('clearAuth')
    },
    startLoading({ commit }) {
      commit('setLoading', true)
    },
    stopLoading({ commit }) {
      commit('setLoading', false)
    },
    setPatient({ commit }, patient) {
      commit('setCurrentPatient', patient)
    },
    clearPatient({ commit }) {
      commit('clearCurrentPatient')
    }
  },
  modules: {
    // 可以在这里添加模块
  }
})
